package lostland.gmud.exv2;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

import lostland.gmud.exv2.community.GmudUser;
import lostland.gmud.exv2.data.GmudMap;
import lostland.gmud.exv2.expand.GmudPayment;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.bmob.pay.tool.BmobPay;
import com.bmob.pay.tool.PayListener;
import com.orhanobut.logger.Logger;
import com.tencent.mid.api.MidService;
import com.tencent.stat.StatService;


public class PaymentActivity extends Activity implements View.OnClickListener {

	ProgressDialog dialog;

	String name;
	String body;

	BmobPay bmobPay;

	double price;

	Game game;

	GmudPayment payment = new GmudPayment();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.dialog_pay);
		game = Game.getInstance();

		price = getIntent().getDoubleExtra("price", 50);

		bmobPay = new BmobPay(game);

		findViewById(R.id.btnPayByAli).setOnClickListener(this);
		findViewById(R.id.btnPayByWx).setOnClickListener(this);

		findViewById(R.id.btnAbortPay).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				PaymentActivity.this.setResult(RESULT_CANCELED);
				finish();
			}
		});

	}


	void showDialog(String message) {
		if(dialog == null) {
			dialog = new ProgressDialog(this);
			dialog.setCancelable(false);
		}
		dialog.setMessage(message);
		dialog.show();
	}

	void hideDialog() {
		if(dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
	}

	void installBmobPayPlugin(String fileName) {
		try {
			InputStream is = getAssets().open(fileName);
			File file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + fileName);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();

			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.parse("file://" + file),
					"application/vnd.android.package-archive");
			Game.getInstance().startActivity(intent);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public void onClick(View v) {
		name = ((EditText) findViewById(R.id.etPayNickname)).getText().toString();

		if(name.trim().isEmpty()) {
			name = "匿名用户";
		}


		body = "MID：" + MidService.getMid(game) + "  Saying：" + ((EditText) findViewById(R.id.etPaySaying)).getText().toString();

		if(body.length() > 250) {
			body = body.substring(0, 250); //太长会报错。。。
		}
		payment.setName(name);
		payment.setBody(body);
		payment.setMid(MidService.getMid(game));
		if(GmudUser.getInstance() != null) {
			payment.setCommunityUsername(GmudUser.getInstance().getUsername());
		}

		if(v.getId() == R.id.btnPayByAli) {
			showDialog("正在获取订单...");

			bmobPay.pay(price, name + "的购买", body, new PayListener() {

				// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
				@Override
				public void unknow() {
					Toast.makeText(game, "支付结果未知", Toast.LENGTH_SHORT).show();

					hideDialog();

					onUnknow();
				}

				// 支付成功,如果金额较大请手动查询确认
				@Override
				public void succeed() {

					onSucceed();

					hideDialog();
				}

				// 无论成功与否,返回订单号
				@Override
				public void orderId(String orderId) {
					// 此处应该保存订单号,比如保存进数据库等,以便以后查询

					saveOrderId(orderId);
					showDialog("获取订单成功!请等待跳转到支付页面~");
				}

				// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
				@Override
				public void fail(int code, String reason) {
					Toast.makeText(game, "支付中断!", Toast.LENGTH_SHORT)
					.show();

					if(!payment.getOrderID().getValue().isEmpty()) {
						Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
						Gmud.paymentData.saveLocal();
					}
					hideDialog();
				}
			});
		} else if(v.getId() == R.id.btnPayByWx) {
			showDialog("正在获取订单...");

			bmobPay.payByWX(price, name + "的购买", body, new PayListener() {

				// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
				@Override
				public void unknow() {
					Toast.makeText(game, "支付结果未知,请稍后手动查询", Toast.LENGTH_SHORT).show();
					onUnknow();
					hideDialog();
				}

				// 支付成功,如果金额较大请手动查询确认
				@Override
				public void succeed() {
					onSucceed();
					hideDialog();
				}

				// 无论成功与否,返回订单号
				@Override
				public void orderId(String orderId) {
					// 此处应该保存订单号,比如保存进数据库等,以便以后查询
					saveOrderId(orderId);
					showDialog("获取订单成功!请等待跳转到支付页面~");
				}

				// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
				@Override
				public void fail(int code, String reason) {

					// 当code为-2,意味着用户中断了操作
					// code为-3意味着没有安装BmobPlugin插件
					if(code == -3) {
						new AlertDialog.Builder(PaymentActivity.this)
						.setMessage(
								"你尚未安装支付插件，是否安装插件或改用支付宝支付？")
								.setPositiveButton("安装",
										new DialogInterface.OnClickListener() {

									@Override
									public void onClick(
											DialogInterface dialog1,
											int which) {
										installBmobPayPlugin("BmobPayPlugin.apk");
									}
								})
								.setNegativeButton("支付宝支付",
										new DialogInterface.OnClickListener() {

									@Override
									public void onClick(
											DialogInterface dialog1,
											int which) {
										showDialog("正在获取订单...");

										bmobPay.pay(price, name, body, new PayListener() {

											// 因为网络等原因,支付结果未知(小概率事件),出于保险起见稍后手动查询
											@Override
											public void unknow() {
												Toast.makeText(game, "支付结果未知,请稍后手动查询", Toast.LENGTH_SHORT).show();
												hideDialog();
												onUnknow();
											}

											// 支付成功,如果金额较大请手动查询确认
											@Override
											public void succeed() {
												onSucceed();
												hideDialog();
											}

											// 无论成功与否,返回订单号
											@Override
											public void orderId(String orderId) {
												// 此处应该保存订单号,比如保存进数据库等,以便以后查询

												saveOrderId(orderId);
												showDialog("获取订单成功!请等待跳转到支付页面~");
											}

											// 支付失败,原因可能是用户中断支付操作,也可能是网络原因
											@Override
											public void fail(int code, String reason) {
												Toast.makeText(game, "支付中断!", Toast.LENGTH_SHORT)
												.show();

												if(!payment.getOrderID().getValue().isEmpty()) {
													Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
													Gmud.paymentData.saveLocal();
												}
												hideDialog();
											}
										});
									}
								}).create().show();
					} else {
						Toast.makeText(game, "支付中断!",
								Toast.LENGTH_SHORT).show();
					}
					if(!payment.getOrderID().getValue().isEmpty()) {
						Gmud.paymentData.payments.remove(payment.getOrderID().getValue());
						Gmud.paymentData.saveLocal();
					}
					hideDialog();
				}
			});
		}
	}


	/**
	 * @param orderId
	 */
	private void saveOrderId(String orderId) {

		payment.setOrderID(orderId);

		Properties prop = new Properties();
		prop.setProperty("money", payment.getMoney().getValue());
		prop.setProperty("call_name", payment.getName());
		prop.setProperty("body", payment.getBody());
		prop.setProperty("community_username", payment.getCommunityUsername());
		prop.setProperty("orderid", payment.getOrderID().getValue());
		prop.setProperty("mid", payment.getMid().getValue());

		StatService.trackCustomKVEvent(game, "ev_pay_orderid", prop);


		Gmud.paymentData.payments.put(orderId, payment);
		Gmud.paymentData.saveLocal();

		payment.save(game, new SaveListener() {

			@Override
			public void onFailure(int arg0, String arg1) {
			}

			@Override
			public void onSuccess() {
				Logger.i(payment.getObjectId());
			}
		});

	}


	/**
	 *
	 */
	private void onUnknow() {
		if(Gmud.paymentData.paymentStatus == Gmud.PaymentStatus.TRIAL ||
				Gmud.paymentData.paymentStatus == Gmud.PaymentStatus.TRIAL2) {
			Gmud.paymentData.paymentStatus = Gmud.PaymentStatus.ZERO;
		}
		Gmud.paymentData.saveLocal();
		game.popToRootScreen();

		this.setResult(RESULT_OK);
		finishActivity(0);

		Gmud.maps[1].setEvent(12, 8, -1);
		Gmud.maps[1].setWalkable(12, 8, GmudMap.MP_WALKABLE);
	}


	/**
	 *
	 */
	private void onSucceed() {

		Properties prop = new Properties();
		prop.setProperty("money", payment.getMoney().getValue());
		prop.setProperty("call_name", payment.getName());
		prop.setProperty("body", payment.getBody());
		prop.setProperty("community_username", payment.getCommunityUsername());
		prop.setProperty("orderid", payment.getOrderID().getValue());
		prop.setProperty("mid", payment.getMid().getValue());

		StatService.trackCustomKVEvent(game, "ev_pay_success", prop);

		payment.setPaymentStatus("SUCCESS");
		Toast.makeText(game, "支付成功，非常感谢您的支持！", Toast.LENGTH_SHORT).show();
		payment.update(game, new UpdateListener() {

			@Override
			public void onFailure(int arg0, String arg1) {
				Logger.e(arg0 + arg1);
			}

			@Override
			public void onSuccess() {
				// TODO 自动生成的方法存根

			}
		});
		Gmud.paymentData.paymentStatus = Gmud.PaymentStatus.PAID;
		Gmud.paymentData.saveLocal();
		game.setRectangleStone(name);
		game.popToRootScreen();


		Gmud.maps[1].setEvent(12, 8, -1);
		Gmud.maps[1].setWalkable(12, 8, GmudMap.MP_WALKABLE);

		Gmud.maps[2].setEvent(10, 7, -1);
		Gmud.maps[2].setWalkable(10, 7, GmudMap.MP_WALKABLE);


		this.setResult(RESULT_OK);
		finish();
	}

}
